import 'package:flutter/material.dart';
import '../../models/user_model.dart';

class ChatPage extends StatefulWidget {
  final UserModel targetUser;

  const ChatPage({
    super.key,
    required this.targetUser,
  });

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final List<ChatMessage> _messages = [];
  bool _isRecording = false;

  @override
  void initState() {
    super.initState();
    _loadMessages();
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          children: [
            CircleAvatar(
              radius: 16,
              backgroundColor: Colors.grey[300],
              backgroundImage: widget.targetUser.avatar != null && widget.targetUser.avatar!.isNotEmpty
                  ? NetworkImage(widget.targetUser.avatar!)
                  : null,
              child: widget.targetUser.avatar == null || widget.targetUser.avatar!.isEmpty
                  ? const Icon(Icons.person, size: 18, color: Colors.grey)
                  : null,
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    widget.targetUser.username,
                    style: const TextStyle(fontSize: 16),
                  ),
                  Text(
                    widget.targetUser.isOnline ? '在线' : '离线',
                    style: TextStyle(
                      fontSize: 12,
                      color: widget.targetUser.isOnline
                          ? Colors.green
                          : Colors.grey,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.more_vert),
            onPressed: _showMoreOptions,
          ),
        ],
      ),
      body: Column(
        children: [
          // 消息列表
          Expanded(
            child: ListView.builder(
              controller: _scrollController,
              padding: const EdgeInsets.all(16),
              itemCount: _messages.length,
              itemBuilder: (context, index) {
                final message = _messages[index];
                return _buildMessageItem(message);
              },
            ),
          ),
          // 输入区域
          _buildInputArea(),
        ],
      ),
    );
  }

  Widget _buildMessageItem(ChatMessage message) {
    final isMe = message.isFromMe;

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      child: Row(
        mainAxisAlignment:
            isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isMe) ...[
            CircleAvatar(
              radius: 16,
              backgroundColor: Colors.grey[300],
              backgroundImage: widget.targetUser.avatar != null && widget.targetUser.avatar!.isNotEmpty
                  ? NetworkImage(widget.targetUser.avatar!)
                  : null,
              child: widget.targetUser.avatar == null || widget.targetUser.avatar!.isEmpty
                  ? const Icon(Icons.person, size: 18, color: Colors.grey)
                  : null,
            ),
            const SizedBox(width: 8),
          ],
          Flexible(
            child: Column(
              crossAxisAlignment:
                  isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: isMe
                        ? Theme.of(context).primaryColor
                        : Colors.grey[200],
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: _buildMessageContent(message),
                ),
                const SizedBox(height: 4),
                Text(
                  _formatTime(message.timestamp),
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
          if (isMe) ...[
            const SizedBox(width: 8),
            CircleAvatar(
              radius: 16,
              backgroundImage: null,
              backgroundColor: Colors.grey[300],
              child: const Icon(Icons.person, color: Colors.white),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildMessageContent(ChatMessage message) {
    switch (message.type) {
      case MessageType.text:
        return Text(
          message.content,
          style: TextStyle(
            color: message.isFromMe ? Colors.white : Colors.black,
            fontSize: 16,
          ),
        );
      case MessageType.image:
        return ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Image.network(
            message.content,
            width: 200,
            height: 150,
            fit: BoxFit.cover,
          ),
        );
      case MessageType.voice:
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.play_arrow,
              color: message.isFromMe ? Colors.white : Colors.black,
            ),
            const SizedBox(width: 8),
            Text(
              '${message.duration}s',
              style: TextStyle(
                color: message.isFromMe ? Colors.white : Colors.black,
              ),
            ),
          ],
        );
      case MessageType.gift:
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.card_giftcard,
              color: message.isFromMe ? Colors.white : Colors.black,
            ),
            const SizedBox(width: 8),
            Text(
              '发送了${message.content}',
              style: TextStyle(
                color: message.isFromMe ? Colors.white : Colors.black,
              ),
            ),
          ],
        );
    }
  }

  Widget _buildInputArea() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: [
          // 更多功能按钮
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _showMoreActions,
          ),
          // 输入框
          Expanded(
            child: TextField(
              controller: _messageController,
              decoration: InputDecoration(
                hintText: '输入消息...',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(24),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: Colors.grey[100],
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 8,
                ),
              ),
              maxLines: null,
            ),
          ),
          const SizedBox(width: 8),
          // 发送按钮或录音按钮
          GestureDetector(
            onLongPressStart: (_) => _startRecording(),
            onLongPressEnd: (_) => _stopRecording(),
            onTap: _sendTextMessage,
            child: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: Theme.of(context).primaryColor,
                shape: BoxShape.circle,
              ),
              child: Icon(
                _isRecording ? Icons.mic : Icons.send,
                color: Colors.white,
                size: 20,
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _showMoreActions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                _buildActionButton(
                  icon: Icons.photo,
                  label: '相册',
                  onTap: () {
                    Navigator.pop(context);
                    _selectImage();
                  },
                ),
                _buildActionButton(
                  icon: Icons.camera_alt,
                  label: '拍照',
                  onTap: () {
                    Navigator.pop(context);
                    _takePhoto();
                  },
                ),
                _buildActionButton(
                  icon: Icons.card_giftcard,
                  label: '礼物',
                  onTap: () {
                    Navigator.pop(context);
                    _showGiftDialog();
                  },
                ),
                _buildActionButton(
                  icon: Icons.location_on,
                  label: '位置',
                  onTap: () {
                    Navigator.pop(context);
                    _shareLocation();
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(icon, color: Colors.grey[700]),
          ),
          const SizedBox(height: 8),
          Text(
            label,
            style: const TextStyle(fontSize: 12),
          ),
        ],
      ),
    );
  }

  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.person),
              title: const Text('查看资料'),
              onTap: () {
                Navigator.pop(context);
                // 跳转到用户资料页
              },
            ),
            ListTile(
              leading: const Icon(Icons.phone),
              title: const Text('语音通话'),
              onTap: () {
                Navigator.pop(context);
                // 发起语音通话
              },
            ),
            ListTile(
              leading: const Icon(Icons.videocam),
              title: const Text('视频通话'),
              onTap: () {
                Navigator.pop(context);
                // 发起视频通话
              },
            ),
            ListTile(
              leading: const Icon(Icons.block),
              title: const Text('拉黑'),
              onTap: () {
                Navigator.pop(context);
                // 拉黑用户
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showGiftDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择礼物'),
        content: SizedBox(
          width: double.maxFinite,
          height: 300,
          child: GridView.builder(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              crossAxisSpacing: 8,
              mainAxisSpacing: 8,
            ),
            itemCount: 9,
            itemBuilder: (context, index) {
              final gifts = [
                '🌹',
                '💝',
                '🎁',
                '💎',
                '🏆',
                '⭐',
                '🎈',
                '🍰',
                '🎪'
              ];
              return GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                  _sendGift(gifts[index]);
                },
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Center(
                    child: Text(
                      gifts[index],
                      style: const TextStyle(fontSize: 32),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  void _loadMessages() {
    // 模拟加载消息
    _messages.addAll([
      ChatMessage(
        id: '1',
        content: '你好！我是${widget.targetUser.username}',
        type: MessageType.text,
        isFromMe: false,
        timestamp: DateTime.now().subtract(const Duration(minutes: 5)),
      ),
      ChatMessage(
        id: '2',
        content: '你好！很高兴认识你',
        type: MessageType.text,
        isFromMe: true,
        timestamp: DateTime.now().subtract(const Duration(minutes: 4)),
      ),
      ChatMessage(
        id: '3',
        content: '这是一条图片消息',
        type: MessageType.image,
        isFromMe: false,
        timestamp: DateTime.now().subtract(const Duration(minutes: 3)),
      ),
    ]);
  }

  void _sendTextMessage() {
    final text = _messageController.text.trim();
    if (text.isNotEmpty) {
      final message = ChatMessage(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        content: text,
        type: MessageType.text,
        isFromMe: true,
        timestamp: DateTime.now(),
      );
      setState(() {
        _messages.add(message);
      });
      _messageController.clear();
      _scrollToBottom();
    }
  }

  void _selectImage() {
    // 处理选择图片逻辑
    final message = ChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      content: '',
      type: MessageType.image,
      isFromMe: true,
      timestamp: DateTime.now(),
    );
    setState(() {
      _messages.add(message);
    });
    _scrollToBottom();
  }

  void _takePhoto() {
    // 处理拍照逻辑
    _selectImage();
  }

  void _sendGift(String gift) {
    final message = ChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      content: gift,
      type: MessageType.gift,
      isFromMe: true,
      timestamp: DateTime.now(),
    );
    setState(() {
      _messages.add(message);
    });
    _scrollToBottom();
  }

  void _shareLocation() {
    // 处理分享位置逻辑
  }

  void _startRecording() {
    setState(() {
      _isRecording = true;
    });
  }

  void _stopRecording() {
    setState(() {
      _isRecording = false;
    });
    // 处理录音结束逻辑
    final message = ChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      content: '语音消息',
      type: MessageType.voice,
      isFromMe: true,
      timestamp: DateTime.now(),
      duration: 5,
    );
    setState(() {
      _messages.add(message);
    });
    _scrollToBottom();
  }

  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
}

class ChatMessage {
  final String id;
  final String content;
  final MessageType type;
  final bool isFromMe;
  final DateTime timestamp;
  final int? duration;

  ChatMessage({
    required this.id,
    required this.content,
    required this.type,
    required this.isFromMe,
    required this.timestamp,
    this.duration,
  });
}

enum MessageType {
  text,
  image,
  voice,
  gift,
}
